package com.liuhengjia.aiknowledgebase.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.liuhengjia.aiknowledgebase.common.MessageWrapper;
import com.liuhengjia.aiknowledgebase.entity.BaseConversation;
import com.liuhengjia.aiknowledgebase.service.BaseConversationService;
import com.liuhengjia.aiknowledgebase.service.ChatService;
import com.liuhengjia.aiknowledgebase.api.response.ConversationVO;
import com.liuhengjia.aiknowledgebase.util.Ids;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.List;

import org.springframework.util.StringUtils;

/**
 * 聊天服务层实现类
 */
@Service
@RequiredArgsConstructor
public class ChatServiceImpl implements ChatService {
    private final BaseConversationService baseConversationService;

    @Override
    public ConversationVO create() {
        String conversationId = Ids.generate32UUID();
        String title = "New Chat";
        baseConversationService.save(BaseConversation.builder().conversationId(conversationId).title(title).build());
        return ConversationVO.builder().conversationId(conversationId).title(title).build();
    }

    @Override
    public void edit(String conversationId, String title) {
        if (!StringUtils.hasText(title)) {
            return;
        }
        baseConversationService.update(
                BaseConversation.builder().title(title).build(),
                new LambdaQueryWrapper<BaseConversation>().eq(BaseConversation::getConversationId, conversationId)
        );
    }

    @Override
    public List<ConversationVO> list() {
        return baseConversationService.list(new LambdaQueryWrapper<BaseConversation>().orderByAsc(BaseConversation::getCreatedTime))
                .stream()
                .map(v -> ConversationVO.builder().conversationId(v.getConversationId()).title(v.getTitle()).build())
                .toList();
    }

    @Override
    public void delete(String conversationId) {
        baseConversationService.remove(new LambdaQueryWrapper<BaseConversation>().eq(BaseConversation::getConversationId, conversationId));
    }

    @Override
    public ConversationVO get(String conversationId) {
        return baseConversationService.getOneOpt(
                        new LambdaQueryWrapper<BaseConversation>().eq(BaseConversation::getConversationId, conversationId))
                .map(v -> ConversationVO.builder().conversationId(v.getConversationId())
                        .title(v.getTitle())
                        .messages(MessageWrapper.fromConversationStr(v.getContent()))
                        .build()
                ).orElseThrow(() -> new RuntimeException("找不到 ID 的对话：%s ".formatted(conversationId)));

    }
}
